package sk.mka.phd.timit.data;

import java.util.ArrayList;
import org.apache.log4j.Logger;
import sk.mka.phd.files.reader.load.arbitrary.ArbitraryDataLoadFileImpl;
import sk.mka.phd.timit.storage.IPhonemeStorage;
import sk.mka.phd.timit.storage.PhonemeStorage;

/**
 *
 * @author katrami
 * @date Aug 20, 2010
 */
public final class LoadFileOutputDataImpl extends ArbitraryDataLoadFileImpl {

    private final static Logger log = Logger.getLogger(LoadFileOutputDataImpl.class);

    public LoadFileOutputDataImpl(String finalPath, String separator) {
        super(finalPath, separator);
    }

    /*
     * Iterate throught all output files and found id of value 1, finding winner
     * TODO create 40 cols.size dimension array for input and output only one array for
     * application
     * best choice will be to create singleton 
     */
    public void findWinner(final IPhonemeStorage phonemeStorageSingleton) {
        ArrayList<Object> lines = getLines();
        Object col;
        ArrayList<Integer> outputIds = new ArrayList<Integer>(); //save output id for output
        for (int i = 0; i < lines.size(); i++) {

            ArrayList cols = (ArrayList) lines.get(i);

            if (!PhonemeStorage.showedStorageDimension) {
                log.debug("cols: = " + cols.size());
                PhonemeStorage.showedStorageDimension = true;
            }
            int x = 0;

            for (int j = 0; j < cols.size(); j++) {
                col = cols.get(j);
                final Integer winner = Integer.valueOf(col.toString());
                if (winner == 1) {
                    outputIds.add(j);
                }
                x++;
            }

        }
        divideInputPhonemeByOutputId(outputIds, phonemeStorageSingleton);

    }

    /**
     *
     * @param outputId output ides for loading inputs
     * @param phonemeStorageSingleton
     */
    private final void divideInputPhonemeByOutputId(ArrayList<Integer> outputIds, final IPhonemeStorage phonemeStorageSingleton) {

        int indexOfStartExtension = finalPath.indexOf("_");
        String inputPath = finalPath.substring(0, indexOfStartExtension) + "_in.csv";
        log.info(inputPath);

        ArbitraryDataLoadFileImpl inputFile = new ArbitraryDataLoadFileImpl(inputPath, ",");
        ArrayList<Object> lines = inputFile.getLines();
        for (int i = 0; i < lines.size(); i++) {
            Integer winnerId = outputIds.get(i);
            ArrayList cols = (ArrayList) lines.get(i);

            //phonemeStorageSingleton.saveInput(winnerId, cols);
            phonemeStorageSingleton.saveToFile(winnerId, cols);
        }
    }
}
